<template>
  <a-spin :spinning="loading">
    <div class="overview-staff-wrapper">
      <div class="headBox">
        <div style="display: flex; align-items: center">
          <selectCompanyGroup />
          <a-month-picker :allowClear="false" placeholder="选择月份" v-model="date" style="margin-left: 32px" @change="onMonthChange" />
        </div>
        <a-button type="primary" @click="showAdd"><a-icon type="container" />生成明细表</a-button>
      </div>
      <a-modal v-model="addVisible" title="生成明细表" @ok="handleAddOk">
        <a-form-model ref="ruleForm" :model="addForm" :label-col="labelCol" :wrapper-col="wrapperCol" style="margin-top: 15px">
          <a-form-model-item
            :rules="{
              required: true,
              message: '请选择'
            }"
            ref="date"
            label="明细表月份"
            prop="date"
          >
            <a-month-picker placeholder="请选择月份" v-model="addForm.date" style="width: 240px" />
          </a-form-model-item>
          <a-form-model-item
            :rules="{
              required: true,
              message: '请选择'
            }"
            ref="companyInfoList"
            label="选择用工单位"
            prop="companyInfoList"
          >
            <a-tree-select
              v-model="addForm.companyInfoList"
              :tree-data="companyDataList"
              :filterTreeNode="false"
              @search="treeSearch"
              :replaceFields="replaceFields2"
              labelInValue
              tree-checkable
              placeholder="请选择"
              style="width: 240px"
            />
          </a-form-model-item>
          <a-form-model-item
            :rules="{
              required: true,
              message: '请选择'
            }"
            ref="type"
            label="明细表类型"
            prop="type"
          >
            <a-select placeholder="请选择" v-model="addForm.type" style="width: 240px">
              <a-select-option value="customer"> 客户明细表 </a-select-option>
              <a-select-option value="salary"> 薪资明细表 </a-select-option>
              <a-select-option value="social"> 社保明细表 </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
            v-if="addForm.type === 'customer' || addForm.type === 'salary'"
            :rules="{
              required: true,
              message: '请选择'
            }"
            ref="date"
            label="薪资数据来源月份"
            prop="date"
          >
            <a-month-picker placeholder="请选择月份" v-model="addForm.salaryDate" style="width: 240px" />
          </a-form-model-item>
          <a-form-model-item
            v-if="addForm.type === 'customer' || addForm.type === 'social'"
            :rules="{
              required: true,
              message: '请选择'
            }"
            ref="date"
            label="社保数据来源月份"
            prop="date"
          >
            <a-month-picker placeholder="请选择月份" v-model="addForm.socialDate" style="width: 240px" />
          </a-form-model-item>
        </a-form-model>
      </a-modal>
      <div style="display: flex; padding: 8px 0 12px 0">
        <div :class="tabButtonKehu ? 'tabButton' : 'tabButtonNot'" @click="tabChange(3)">客户明细</div>
        <div :class="tabButtonXinzi ? 'tabButton' : 'tabButtonNot'" @click="tabChange(1)">薪资明细</div>
        <div :class="tabButtonShebao ? 'tabButton' : 'tabButtonNot'" @click="tabChange(2)">社保明细</div>
      </div>

      <div v-if="groupList && groupList.length">
        <div v-for="(item, index) in groupList" :key="index">
          <div class="fix-item-wrapper">
            <div class="fix-item-one">
              <div class="fix-item-name">
                <div
                  v-if="!item.isOpen && item.hrMonthlySalarySummaryVOList && item.hrMonthlySalarySummaryVOList.length > 0"
                  class="showIcon"
                  style="cursor: pointer"
                  @click="openClick(item)"
                >
                  <a-icon type="plus" />
                </div>
                <div
                  v-if="item.isOpen && item.hrMonthlySalarySummaryVOList && item.hrMonthlySalarySummaryVOList.length > 0"
                  class="showIcon"
                  style="cursor: pointer"
                  @click="openClick(item)"
                >
                  <a-icon type="minus" />
                </div>
                <div
                  v-if="!item.hrMonthlySalarySummaryVOList || item.hrMonthlySalarySummaryVOList.length === 0"
                  class="noShowIcon"
                  style="cursor: pointer"
                >
                  <a-icon type="file-text" theme="filled" />
                </div>
                <a-tooltip :title="item.name">
                  <div style="width: 75%; overflow: hidden; word-break: break-all; text-overflow: ellipsis">{{ item.name }}</div>
                </a-tooltip>
              </div>
            </div>
            <div class="fix-item-two">
              <div style="width: 25%; text-align: center; text-align: left">
                <div class="childpProjectName">
                  {{ customerDetailsType === "customer" ? "本月人数" : customerDetailsType === "salary" ? "本月计薪人数" : "本月参保人数" }}
                </div>
                <div class="childContentName">{{ item.empNumber ? item.empNumber : 0 }}人</div>
              </div>
              <div style="width: 25%; text-align: center; text-align: left" v-if="customerDetailsType === 'salary'">
                <div class="childpProjectName">应发工资</div>
                <div class="childContentName">{{ item.shouldWages ? item.shouldWages : 0 }}元</div>
              </div>
              <div style="width: 25%; text-align: center; text-align: left" v-if="customerDetailsType === 'salary'">
                <div class="childpProjectName">实发工资</div>
                <div class="childContentName">{{ item.paidWages ? item.paidWages : 0 }}元</div>
              </div>
              <div style="width: 25%; text-align: center; text-align: left" v-if="customerDetailsType === 'social'">
                <div class="childpProjectName">企业社保</div>
                <div class="childContentName">{{ item.enterpriseSocialSecurity ? item.enterpriseSocialSecurity : 0 }}元</div>
              </div>
              <div style="width: 25%; text-align: center; text-align: left" v-if="customerDetailsType === 'social'">
                <div class="childpProjectName">企业公积金</div>
                <div class="childContentName">{{ item.enterpriseProvidentFund ? item.enterpriseProvidentFund : 0 }}元</div>
              </div>
              <div style="width: 25%; text-align: center; text-align: left" v-if="customerDetailsType === 'customer'">
                <div class="childpProjectName">人力成本</div>
                <div class="childContentName">{{ item.laborCost ? item.laborCost : 0 }}元</div>
              </div>
              <div style="width: 25%; text-align: center; text-align: left">
                <div class="childpProjectName">服务费</div>
                <div class="childContentName">{{ item.serviceCharge ? item.serviceCharge : 0 }}元</div>
              </div>
              <div style="width: 25%; text-align: center; text-align: left">
                <div class="childpProjectName">客户费用</div>
                <div class="childContentName">{{ item.customerFees ? item.customerFees : 0 }}元</div>
              </div>
            </div>
            <div class="fix-item-three">
              <div>
                <a-button type="link" @click="goDetail(item)">详情</a-button>
                <a-popconfirm :title="'确定删除?'" @confirm="deleteItem(item)">
                  <a-icon slot="icon" type="question-circle-o" style="color: red" />
                  <a-button v-if="!item.hrMonthlySalarySummaryVOList || item.hrMonthlySalarySummaryVOList.length === 0" type="link">
                    删除
                  </a-button>
                </a-popconfirm>
              </div>
            </div>
          </div>
          <ItemCustomer
            :target="item"
            :customerDetailsType="customerDetailsType"
            :showDetail="false"
            @openClick="openClick"
            @goDetail="goDetail"
            @deleteItem="deleteItem"
          />
        </div>
      </div>
      <div v-else style="padding: 120px 0px 560px 0px; background-color: #f2f3f5">
        <a-empty />
      </div>
    </div>
  </a-spin>
</template>

<script>
import selectCompanyGroup from "@/components/SelectCompany";
import { findCompanyGroup } from "@/api/company/contract";
import { getCompany, addCustomer, getDate, deleteItem } from "./api";
import moment from "moment";
import { mapState } from "vuex";
import ItemCustomer from "./itemCustomer.vue";

export default {
  components: {
    ItemCustomer,
    selectCompanyGroup
  },
  data() {
    return {
      paramType: null,
      addForm: {},
      tabButtonXinzi: false,
      tabButtonShebao: false,
      tabButtonKehu: true,
      loading: false,
      dataList: [],
      companyDataList: [],
      labelCol: { span: 8 },
      wrapperCol: { span: 12 },
      date: moment(moment().format("YYYY-MM"), "YYYY-MM"),
      customerDetailsType: "customer",
      isOpen: false,
      addVisible: false,
      treeSiteName: undefined,
      groupList: [],
      companyList: [],
      flatDataList: [],
      replaceFields2: {
        children: "companyList",
        title: "name",
        key: "uuid",
        value: "uuid"
      }
    };
  },
  computed: {
    ...mapState(["site"]),
    type() {
      return this.site.selectType;
    },
    selectTreeId() {
      return this.site.selectId;
    },
    siteName() {
      return this.site.selectName;
    }
  },
  watch: {
    siteName: {
      handler() {
        this.dataList = this.site.companyTree ? JSON.parse(this.site.companyTree) : [];
        console.log(this.dataList);
        this.getDate();
      },
      immediate: true
    }
  },
  created() {},
  methods: {
    deleteItem(e) {
      deleteItem(e.customerDetailsIds[0])
        .then((res) => {
          this.$notification["success"]({
            message: "success",
            description: "删除成功"
          });
          this.getDate();
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    getDate() {
      getDate().then((res) => {
        if (this.$route.query.date) {
          this.date = moment(this.$route.query.date, "YYYY-MM");
        } else if (res.data && res.data.yearly && res.data.monthly) {
          this.date = moment(`${res.data.yearly}` + "-" + `${res.data.monthly}`, "YYYY-MM");
        } else {
          this.date = moment(moment().format("YYYY-MM"), "YYYY-MM");
        }
        this.findCompanyGroup();
        this.getList();
      });
    },
    treeSearch(e) {
      this.findCompanyGroup(e);
    },
    showAdd() {
      this.addVisible = true;
      this.addForm = {};
    },
    findCompanyGroup(e) {
      findCompanyGroup({ name: e || null })
        .then((res) => {
          this.companyDataList = this.addTreeSlot(res.data);
          this.flatten(this.companyDataList);
          this.addForm.companyInfoList = this.addForm.companyInfoList
            ? JSON.parse(JSON.stringify(this.addForm.companyInfoList))
            : undefined;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    addTreeSlot(data) {
      if (!data) {
        return [];
      }
      data.forEach((el) => {
        el.scopedSlots = { title: "custom" };
        this.addTreeSlot(el.companyList);
      });
      return data;
    },
    flatten(list) {
      if (list !== null) {
        list.forEach((item) => {
          this.flatDataList.push(item);
          this.flatten(item.companyList);
        });
      }
    },
    handleAddOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          var companyArr = [];
          this.addForm.companyInfoList.forEach((item) => {
            this.flatDataList.forEach((item2, index2) => {
              if (item2.uuid && item2.uuid === item.value) {
                companyArr.push({ companyId: item2.id, companyName: item2.name });
              }
            });
          });
          addCustomer({
            companyId: this.$store.state.hr.companyId,
            monthly: moment(this.addForm.date).format("MM"),
            type: this.addForm.type,
            yearly: moment(this.addForm.date).format("YYYY"),
            salaryMonthly: this.addForm.salaryDate ? moment(this.addForm.salaryDate).format("MM") : undefined,
            salaryYearly: this.addForm.salaryDate ? moment(this.addForm.salaryDate).format("YYYY") : undefined,
            socialMonthly: this.addForm.socialDate ? moment(this.addForm.socialDate).format("MM") : undefined,
            socialYearly: this.addForm.socialDate ? moment(this.addForm.socialDate).format("YYYY") : undefined,
            companyInfoList: companyArr
          }).then((res) => {
            this.addVisible = false;
            this.getCompanyList();
          });
        }
      });
    },
    tabChange(e) {
      if (e === 1) {
        this.tabButtonXinzi = true;
        this.tabButtonShebao = false;
        this.tabButtonKehu = false;
        this.customerDetailsType = "salary";
      } else if (e === 2) {
        this.tabButtonXinzi = false;
        this.tabButtonShebao = true;
        this.tabButtonKehu = false;
        this.customerDetailsType = "social";
      } else if (e === 3) {
        this.tabButtonXinzi = false;
        this.tabButtonShebao = false;
        this.tabButtonKehu = true;
        this.customerDetailsType = "customer";
      }
      this.getCompanyList();
    },
    getList() {
      if (this.selectTreeId === "-1" || this.selectTreeId === null || this.selectTreeId === undefined) {
        this.paramType = {
          id: this.dataList[0].id,
          type: this.dataList[0].type
        };
      } else {
        this.paramType = {
          id: this.selectTreeId,
          type: this.type
        };
      }
      this.getCompanyList();
    },
    goDetail(item) {
      this.$router.push({
        path: "customers/customerDetail",
        query: {
          dataList: JSON.stringify(item),
          monthly: moment(this.date).format("MM"),
          yearly: moment(this.date).format("YYYY"),
          formType: this.customerDetailsType
        }
      });
    },
    getCompanyList() {
      this.loading = true;
      this.groupList = [];
      getCompany({
        monthly: moment(this.date).format("MM"),
        yearly: moment(this.date).format("YYYY"),
        type: this.paramType,
        customerDetailsType: this.customerDetailsType
      })
        .then((res) => {
          this.groupList = JSON.parse(JSON.stringify(res.data));
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          console.log("debug log --> ", err);
        });
    },
    openClick(e) {
      console.log(e);
      e.isOpen = !e.isOpen;
      this.groupList = JSON.parse(JSON.stringify(this.groupList));
    },
    // 月份选择变化
    onMonthChange(e) {
      this.date = e;
      const query = JSON.parse(JSON.stringify(this.$router.history.current.query)); // 取当前路由query值并且深拷贝
      const path = this.$router.history.current.path; // 取当前路由地址
      query.date = moment(this.date).format("YYYY-MM"); // 修改变动的query值
      this.$router.push({ path, query }); // 改变query值
      this.getCompanyList();
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .ant-select-selection--multiple {
  max-height: 400px;
  overflow-y: auto;
}

.headBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f2f3f5;
  border-radius: 4px;
  // padding: 16px 24px;
  margin-bottom: 8px;
}
.showIcon {
  width: 32px;
  height: 32px;
  background: var(--primary10);
  border-radius: 8px;
  margin-right: 12px;
  color: var(--primary);
  line-height: 32px;
  text-align: center;
}
.noShowIcon {
  width: 32px;
  height: 32px;
  background: var(--primary);
  border-radius: 8px;
  margin-right: 12px;
  color: #ffffff;
  line-height: 32px;
  text-align: center;
}

.fix-item-wrapper {
  display: flex;
  height: 100px;
  background: #ffffff;
  border-radius: 8px;
  padding-left: 24px;

  // border: 1px solid #e8e8e8;
  align-items: center;
  display: flex;
  margin-top: 12px;
  .childpProjectName {
    font-size: 14px;
    font-weight: 300;
    color: #767885;
  }
  .childContentName {
    font-size: 20px;
    font-weight: 500;
    color: #55565d;
  }
  .fix-item-one {
    height: 40px;
    display: flex;
    align-self: center;
    padding-left: 10px;
    width: 20%;
    border-right: 1px solid #e8e8e8;
  }
  .fix-item-two {
    padding-left: 45px;
    margin-top: 10px;
    width: 65%;
    height: 45px;
    padding-right: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-right: 1px solid #e8e8e8;
  }
  .fix-item-three {
    width: 15%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .fix-item-name {
    width: 100%;
    padding-right: 20px;
    font-size: 18px;
    font-weight: 500;
    margin-top: 6px;
    color: #222426;
    display: flex;
    overflow: hidden;
    word-break: break-all; //强行换行,将截断英文单词
    text-overflow: ellipsis; //当元素内文本溢出时（超过width部分）显示省略标记（...）
    white-space: nowrap;
  }
}

.overview-staff-wrapper {
  .tabButton {
    width: 91px;
    height: 32px;
    background: var(--primary);
    border-radius: 16px;
    font-size: 14px;
    font-weight: 500;
    line-height: 32px;
    text-align: center;
    color: #ffffff;
    margin-left: 12px;
    cursor: pointer;
  }
  .tabButtonNot {
    width: 91px;
    height: 32px;
    background: #ffffff;
    border-radius: 16px;
    font-size: 14px;
    font-weight: 500;
    line-height: 32px;
    text-align: center;
    margin-left: 12px;
    cursor: pointer;
  }
  .iconfont {
    color: var(--primary);
  }
  .font-title {
    font-size: 16px;
    font-weight: 500;
    color: #55565d;
    line-height: 24px;
  }
}
.iconStyle {
  color: var(--primary);
  margin-right: 10px;
}
</style>
